package com.zy.is.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zy.is.common.api.Result;
import com.zy.is.common.config.AppConstants;
import com.zy.is.common.properties.AppProperties;
import com.zy.is.domain.SysFileInfo;
import com.zy.is.service.SysFileInfoService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * 上传控制器
 *
 * @author Yanzy
 */
@Slf4j
@RestController
@AllArgsConstructor
public class UploadController {

    private final SysFileInfoService sysFileInfoService;

    private final AppProperties appProperties;

    /**
     * 上传文件
     *
     * @param file file
     * @return result
     */
    @PostMapping("/upload/img")
    public Result<String> uploadImg(MultipartFile file) {

        try {
            SysFileInfo sysFileInfo = new SysFileInfo();
            upload(file, sysFileInfo);
            // 保存数据库
            sysFileInfoService.insert(sysFileInfo);
        } catch (IOException e) {
            log.error("文件上传失败: {}", e.getMessage());
            return Result.error("上传失败!!!");
        }
        return Result.success("上传成功");
    }

    private void upload(MultipartFile file, SysFileInfo sysFileInfo) throws IOException {
        if (ObjectUtil.isNotNull(file)) {
            // 获取原始文件名
            String originalFileName = file.getOriginalFilename();
            // 获取文件后缀
            String suffix = StringUtils.substring(originalFileName, StringUtils.indexOf(originalFileName, ".") + 1);

            String fileName = UUID.randomUUID() + "." + suffix;
            // 保存文件服务器路径
            String filePath = appProperties.getFilePath() + File.separator + DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN) + File.separator + fileName;
            // 文件访问路径
            String accessPath = AppConstants.ACCESS_PATH + File.separator + DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN) + File.separator + fileName;

            File saveFile = new File(filePath);
            // 创建文件夹
            if (!saveFile.getParentFile().exists()) {
                saveFile.getParentFile().mkdirs();
            }
            // 复制文件
            file.transferTo(saveFile);

            sysFileInfo.setFileName(fileName);
            sysFileInfo.setFilePath(filePath);
            sysFileInfo.setAccessPath(accessPath);
            sysFileInfo.setFileSuffix(suffix);
            sysFileInfo.setCreateTime(new Date());
        }
    }

    /**
     * 获取
     *
     * @return
     */
    @PostMapping("/file/getList")
    public Result<Page<SysFileInfo>> getFiles(@RequestParam("current") Long current, @RequestParam("size") Long size) {
        Page<SysFileInfo> page = new Page<>();
        page.setSize(size);
        page.setCurrent(current);
        Page<SysFileInfo> allByPage = sysFileInfoService.findAllByPage(page, null);
        return Result.success("数据获取成功.", allByPage);
    }

    @PostMapping("/file/del")
    public Result<String> deleteFile(@RequestParam("id") Long id) {
        // 查询
        SysFileInfo sysFileInfo = sysFileInfoService.findById(id);
        if (null == sysFileInfo) {
            return Result.error("数据失效，刷新重试");
        }
        int count = sysFileInfoService.deleteById(id);
        if (count > 0) {
            FileUtil.del(sysFileInfo.getFilePath());
            return Result.success("删除成功");
        } else {
            return Result.error("删除失败，刷新重试");
        }
    }
}
